package com.nofeng.code.plugin.sharedingdb.config;


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.nofeng.code.plugin.sharedingdb.DynamicDataSource;
import com.nofeng.code.plugin.sharedingdb.model.AtomModel;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;


@Component
@ConfigurationProperties(prefix = "db.config")
@Data
public class DataSourceConfig implements ApplicationContextAware {

    private Map<String, String> datasource;

    private Map<String, AtomModel> realDatasource = new HashMap<>();

    private ApplicationContext curApplication;

    @PostConstruct
    public void init() {
        datasource.forEach((key, value) -> {
            realDatasource.put(key, JSON.parseObject(value, AtomModel.class));
        });
    }

    @Bean
    public DynamicDataSource dataSource() {
        DruidDataSource defaultDataSource = new DruidDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        System.out.println(realDatasource);
        realDatasource.forEach((key, value) -> {
            String url = "jdbc:mysql://" + value.getHost() + ":" + value.getPort() + "/"
                    + value.getDbName() + "?" + value.getParam();
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(value.getUsername());
            druidDataSource.setPassword(value.getPassword());
            druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            targetDataSources.put(key, druidDataSource);
        });

        DynamicDataSource dynamicDataSource = new DynamicDataSource(null, targetDataSources);
        return dynamicDataSource;
    }

    @Override
    public void setApplicationContext(ApplicationContext app) throws BeansException {
        setCurApplication(app);
    }
}
